
package com.cgmnx.admin.web;

import com.cgmnx.admin.web.model.CookieUser;
import com.google.common.base.Charsets;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

/**
 *
 */
@Slf4j
public final class CookieUtil {

    public static final String T_COOKIE_NAME = "_t";
    public static final String U_COOKIE_NAME = "_u";
    public static final String V_COOKIE_NAME = "_v";
    private static final String COOKIE_DOMAIN = "cgmmx.cn";
    private static final String COOKIE_PATH = "/";
    private static final int EXPIRED_TIME = 0;
    private static final String CHARSET_UTF8 = Charsets.UTF_8.name();
    private static final int MINUTES_120 = 60 * 60 * 2;

    public static Cookie setUCookie(HttpServletResponse response, String value) {
        return addCookie(response, U_COOKIE_NAME, value, MINUTES_120);
    }

    public static Cookie setTCookie(HttpServletResponse response, String value) {
        return addCookie(response, T_COOKIE_NAME, value, MINUTES_120);
    }

    public static Cookie setVCookie(HttpServletResponse response, String value) {
        return addCookie(response, V_COOKIE_NAME, value, MINUTES_120);
    }

    /**
     * 设置 Cookie, 过期时间为30分钟
     *
     * @param name  名称
     * @param value 值
     */
    public static Cookie setCookie(HttpServletResponse response, String name, String value) {
        return addCookie(response, name, value, MINUTES_120);
    }

    /**
     * 设置 Cookie, 过期时间自定义
     *
     * @param name   名称
     * @param value  值
     * @param maxAge 过期时间, 单位秒
     */
    public static Cookie addCookie(HttpServletResponse response, String name, String value, int maxAge) {
        Cookie cookie = null;
        try {
            cookie = new Cookie(name, URLEncoder.encode(value, CHARSET_UTF8));
            cookie.setMaxAge(maxAge);
            appendDomainAndPath(cookie);
            response.addCookie(cookie);
        } catch (UnsupportedEncodingException e) {
            log.error("设置cookie失败,错误原因:", e);
        }
        return cookie;
    }


    private static void appendDomainAndPath(final Cookie cookie) {

        if (cookie == null) {
            return;
        }

        cookie.setDomain(COOKIE_DOMAIN);
        cookie.setPath(COOKIE_PATH);


    }


    public static Cookie clearCookie(String cookieName) {
        Cookie cookie = new Cookie(cookieName, StringUtils.EMPTY);
        cookie.setMaxAge(EXPIRED_TIME);
        appendDomainAndPath(cookie);
        return cookie;
    }

    /**
     * 获得指定Cookie的值
     *
     * @param name 名称
     * @return 值
     */
    public static String getCookie(HttpServletRequest request, String name) {
        return getCookie(request, null, name, false);
    }

    /**
     * 获得指定Cookie的值，并删除。
     *
     * @param name 名称
     * @return 值
     */
    public static String getCookie(HttpServletRequest request, HttpServletResponse response, String name) {
        return getCookie(request, response, name, true);
    }

    /**
     * 获得指定Cookie的值
     *
     * @param request   请求对象
     * @param response  响应对象
     * @param name      名字
     * @param isRemoved 是否移除
     * @return 值
     */
    public static String getCookie(HttpServletRequest request, HttpServletResponse response, String name, boolean isRemoved) {

        Cookie[] cookies = request.getCookies();
        if (cookies == null) {
            return null;
        }

        String value = null;
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals(name)) {
                try {
                    value = URLDecoder.decode(cookie.getValue(), CHARSET_UTF8);
                } catch (UnsupportedEncodingException e) {
                    log.error("获取cookie失败,错误原因:", e);
                }
                if (isRemoved) {
                    cookie.setMaxAge(0);
                    response.addCookie(cookie);
                }
                return value;
            }

        }

        return value;
    }

    /**
     * 从request对象中获得cookie,得到CookieUser对象
     *
     * @param req 请求对象
     * @return 登录用户的信息
     */
    public static CookieUser getUser(HttpServletRequest req) {
        Cookie[] cookies = req.getCookies();

        if (ArrayUtils.isEmpty(cookies)) {
            return null;
        }

        String uCookie = null;
        String tCookie = null;
        String vCookie = null;
        if (cookies != null) {
            for (Cookie c : cookies) {
                if (uCookie == null && U_COOKIE_NAME.equals(c.getName())) {
                    uCookie = StringUtils.trim(c.getValue());
                } else if (tCookie == null && T_COOKIE_NAME.equals(c.getName())) {
                    tCookie = StringUtils.trim(c.getValue());
                } else if (vCookie == null && V_COOKIE_NAME.equals(c.getName())) {
                    vCookie = StringUtils.trim(c.getValue());
                }
            }
        }
        return getUser(uCookie, tCookie, vCookie);
    }


    /**
     * 根据用户Cookie得到用户信息
     *
     * @param uCookie 用户登录cookie中的_u
     * @param tCookie 用户登录cookie中的_t
     * @param vCookie 用户登录cookie中的_v
     * @return CookieUser
     */
    public static CookieUser getUser(String uCookie, String tCookie, String vCookie) {

        if (StringUtils.isBlank(uCookie) || StringUtils.isBlank(tCookie) || StringUtils.isBlank(vCookie)) {
            return null;
        }
        CookieUser cookieUser = new CookieUser();
        cookieUser.set_u(uCookie);
        cookieUser.set_t(Long.valueOf(tCookie));
        cookieUser.set_v(vCookie);
        return cookieUser;

    }


}